const db = require('../db')

const DB_NAME = 'BookedDate'

const invalidDaysWithMonth = async (houseId, year, month, type) => {
  const where = {
    houseId,
    year,
    month
  }
  if (type) {
    where.type = type
  }
  const results = await db(DB_NAME)
    .where(where)
    .select()
  
  return results.map(item => `${year}/${month}/${item.date}`)
}

const bookedDaysWithMonth = async (houseId, year, month) => {
  return await invalidDaysWithMonth(houseId, year, month, 1)
}

const closedDaysWithMonth = async (houseId, year, month) => {
  return await invalidDaysWithMonth(houseId, year, month, 2)
}

const isDateAvailable = async (houseId, year, month, date) => {
  const results = await db(DB_NAME)
    .where({
      houseId,
      year,
      month,
      date
    })
    .select()
  return !results.length
}

const add = async (houseId, year, month, date, type) => {
  const available = await isDateAvailable(houseId, year, month, date)
  if (!available) {
    throw new BizError('该日期状态不可变更')
    return
  }
  const result = await db(DB_NAME)
    .returning('id')
    .insert({
      houseId,
      year,
      month,
      date,
      type
    })
  return result[0]
}

const addBooked = async (houseId, year, month, date) => {
  return await add(houseId, year, month, date, 1)
}

const addClosed = async (houseId, year, month, date) => {
  return await add(houseId, year, month, date, 2)
}

const removeClosed = async (houseId, year, month, date) => {
  const result = await db(DB_NAME)
    .where({
      houseId,
      year,
      month,
      date,
      type: 2
    })
    .del()
}

module.exports = {
  invalidDaysWithMonth,
  bookedDaysWithMonth,
  closedDaysWithMonth,
  isDateAvailable,
  addBooked,
  addClosed,
  removeClosed
}